package com.miniapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miniapp.entity.MiniUserTokenEntity;
import com.miniapp.mapper.MiniUserMapper;
import com.miniapp.mapper.MiniUserTokenMapper;
import com.miniapp.oauth2.TokenGenerator;
import com.miniapp.service.MiniUserTokenService;
import com.miniapp.utils.BaseUtils;
import com.miniapp.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 系统用户
 *
 * @author linyuchi
 * @date 2018/03/18
 */
@Service
public class MiniUserTokenServiceImpl  extends BaseServiceImpl<MiniUserTokenMapper,MiniUserTokenEntity>  implements MiniUserTokenService {
	//12小时后过期
	private final static int EXPIRE = 3600 * 12;

	@Resource
	private MiniUserMapper miniUserMapper;

	@Override
	public R createToken(long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		MiniUserTokenEntity tokenEntity = baseMapper.selectOne(new QueryWrapper<MiniUserTokenEntity>().eq("user_id",userId));
		if (BaseUtils.isEmpty(tokenEntity)){
			tokenEntity = new MiniUserTokenEntity();
		}
		tokenEntity.setToken(token);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(expireTime);
		tokenEntity.setUserId(userId);
		//tokenEntity.setMiniUser(MiniUserDao.findOne(userId));
		//保存token
		this.saveOrUpdate(tokenEntity);

		R r = R.ok().put("token", token).put("expire", EXPIRE);
		return r;
	}

	@Override
	public void logout(long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//修改token
		//MiniUserToken tokenEntity = this.findById(userId);
		MiniUserTokenEntity tokenEntity = baseMapper.selectOne(new QueryWrapper<MiniUserTokenEntity>().eq("user_id",userId));

		tokenEntity.setToken(token);
		baseMapper.updateById(tokenEntity);
	}

	@Override
	public MiniUserTokenEntity queryByToken(String token) {
		return baseMapper.selectOne(new QueryWrapper<MiniUserTokenEntity>().eq("token",token));
	}
}
